var util = require('../../utils/util');
var wxRequest = require('../../utils/wxRequest');
import config from '../../utils/config';
import {$wuxLoading} from '../../dist/index';

var app = getApp();
var that;

Page({
  data: {
   cardList:[],
   cardNo: ""
  },
//开启 地域选择键盘
  open: function () { this.setData({ isShow: true, keyBoardType: 1 }); },
  //开启 车牌选择键盘
  openInput: function () { this.setData({ isShow: true, keyBoardType: 2 });},
  //关闭键盘
  close: function () {  this.setData({ isShow: false });},
  //点击了删除
  delete: function (e) {
    this.setData({ cardNo: this.data.cardNo.substring(0, this.data.cardNo.length - 1) });
  },
  //点击键盘
  click: function (e) {
    var val = e.detail;
    if (!val) return;

    //汉字 正则表达式
    var reg = new RegExp('[u4E00-u9FFF]+', 'g');
    if (!reg.test(val)) {
      this.setData({ territory: val, keyBoardType: 2 });
    } else {
      if (this.data.cardNo.length == 8) return;
      this.setData({ cardNo: this.data.cardNo + val });
    }
  },
  //点击了 小键盘确认
  ok: function (e) { 
	that.close();
	if (!that.data.cardNo || that.data.cardNo.length != 8) {

		return false;
    }
	that.postData();
  },
  
  onLoad:function(){
    that = this;
	util.loading = $wuxLoading();
	
    var url = config.myCardList;
    var params = {
    }
    wxRequest.postRequest(url, params) 
    .then(res=>{
        that.setData({
          cardList: res.list
          ,cardNo:""
        });
    })
    .catch(res => {
        util.alert_catch(res.message);
    })
    .finally(function (res) {
        util.hideLoading();
    });

  },
  setCard:function(e){
     
  },


  // 提交表单
  postData: function (e) {  
	that.close();
	 
    if (!that.data.cardNo || that.data.cardNo.length != 8) {
		util.alert("请输入正确的8位卡号");
		return false;
    }

    var url = config.bindCard;
    var params = {
      cardNo: that.data.cardNo
    }
    wxRequest.postRequest(url, params) 
    .then(res=>{
        if(res==1){
          util.alert("添加成功",function(){
            that.onLoad();
          })
        }
    })
    .catch(res => {
        util.alert_catch(res.message);
    })
    .finally(function (res) {
        util.hideLoading();
    });


    
  },

  delCard:function(e){
	  
	util.confirm("确定解绑该卡号?",function(res){
		if (res.confirm) {
            var cardNo = e.target.id;
			var url = config.unbind;
			var params = {
			  cardNo: cardNo
			}
			wxRequest.postRequest(url, params) 
			.then(res=>{
				if(res==1){
					that.setData({
					  cardList: []
					  ,cardNo:""
					});
					util.alert("解绑成功",function(){
						that.onLoad();
					})
				}
			})
			.catch(res => {
				util.alert_catch(res.message);
			})
			.finally(function (res) {
				util.hideLoading();
			});
		}
	});  
	  
	  
    
  }


})
